﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Entities
{
    public class User : BaseEntity
    {
        public string Login { get; set; }
        public string PasswordMD5 { get; set; }
        public List<string> Roles { get; set; }

        public User(User src)
            : base(src.ID)
        {
            this.Login = src.Login;
            this.PasswordMD5 = src.PasswordMD5;
            this.Roles = new List<string>(src.Roles);
        }

        public User(string login, string password, List<string> roles)
            : base(-1)
        {
            if (String.IsNullOrWhiteSpace(login) || String.IsNullOrWhiteSpace(password) || roles == null)
            {
                throw new ArgumentNullException();
            }
            //if (roles.Count == 0)
            //{
            //    throw new ArgumentException();
            //}

            this.Login = login;
            this.PasswordMD5 = GetHash(password);
            this.Roles = roles;
        }
        public User()
            : base(-1)
        {
            this.Roles = new List<string>();
        }

        #region Stolen
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }

        private static string GetHexString(byte[] bt)
        {
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s.Append(((char)(n2 - 10 + (int)'A')));
                else
                    s.Append(n2);
                if (n1 > 9)
                    s.Append(((char)(n1 - 10 + (int)'A')));
                else
                    s.Append(n1);
            }
            return s.ToString();
        }
        #endregion
    }
}
